#!/bin/sh
# 本地Nginx使用nodeport时替换成svc和cluster port
# 使用方法：curl -s https://gitee.com/yunwe/shell/raw/master/proxy_replace.sh | bash -s nginx.conf svc.txt

if [[ ! -e $1 || ! -e $2 ]]; then
  echo "nginx conf 或 k8s 文件不存在！"
fi

source=$(egrep -w '3[0-9]{4}|4[0-9]{4}|5[0-9]{4}|6[0-9]{4}|7[0-9]{4}|8[0-9]{4}' $1)
for s in $source; do
  s_nodeport=$(echo "$s" | egrep -o -w '3[0-9]{4}|4[0-9]{4}|5[0-9]{4}|6[0-9]{4}|7[0-9]{4}|8[0-9]{4}')
  svc=$(grep "$s_nodeport" $2)
  if [[ $svc ]]; then
    svc_name=$(echo $svc | awk '{print $2}')
    svc_namespace=$(echo $svc | awk '{print $1}')
    svc_port=$(echo $svc | cut -d':' -f1 | cut -d'/' -f1 | awk '{print $NF}')
    s_domain=$(echo $s | awk -F'[/:]' '{print $4}')
    if [[ -z "$s_nodeport" || -z "$s_domain" ]]; then
      continue
    fi
    new_proxy_pass=$(echo "$s" | sed "s|${s_nodeport}|${svc_port}|g" | sed "s|${s_domain}|${svc_name}.${svc_namespace}|g")
    #echo "old_proxy_pass: $s , new_proxy_pass: $new_proxy_pass"
    sed -i "s|${s}|${new_proxy_pass}|g" $1
  fi
done

